const http = require('http')
const url = require('url')
const fs = require('fs')

function start (route, port) {
    const html404 = fs.readFileSync('./html/404.html');
    const html50x = fs.readFileSync('./html/50x.html')

    function onRequest (request, response) {
        let pathname = url.parse(request.url).pathname

        console.log('Receive request for ' + pathname)

        let resolve = route(pathname)

        if (resolve && typeof resolve === 'function') {
            try {
                resolve(request, response)
            } catch (e) {
                console.warn(e)
                response.writeHead(500, {'Content-Type': 'text/html'})
                response.write(html50x)
                response.end()
            }
        } else {
            response.writeHead(404, {'Content-Type': 'text/html'})
            response.write(html404)
            response.end()
        }
    }

    http.createServer(onRequest).listen(port)

    console.log('Server is Running at http://127.0.0.1:' + port + '/')
}

exports.start = start
